package com.ruoyi.web.controller.user;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUserUtils;
import com.ruoyi.user.domain.UserAddress;
import com.ruoyi.user.service.UserAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户地址Controller
 *
 * @author ruoyi
 * @date 2024-01-10
 */
@Api(tags = "用户地址")
@RestController
@RequestMapping("/user/address")
public class UserAddressController extends BaseController {
    @Autowired
    private UserAddressService userAddressService;

    /**
     * 查询用户地址列表
     */
    @ApiOperation("查询用户地址列表")
    @PostMapping("/list")
    public TableDataInfo list(UserAddress userAddress) {
        startPage();
        userAddress.setUserId(SecurityUserUtils.getUserId());
        List<UserAddress> list = userAddressService.selectUserAddressList(userAddress);
        return getDataTable(list);
    }

    /**
     * 获取用户地址详细信息
     */
    @ApiOperation("获取用户地址详细信息")
    @PostMapping(value = "/{addressId}")
    public AjaxResult getInfo(@PathVariable("addressId") Long addressId) {
        return success(userAddressService.selectUserAddressByAddressId(addressId));
    }

    /**
     * 新增用户地址
     */
    @ApiOperation("新增用户地址")
    @Log(title = "新增用户地址", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody UserAddress userAddress) {
        return toAjax(userAddressService.insertUserAddress(userAddress));
    }

    /**
     * 修改用户地址
     */
    @ApiOperation("修改用户地址")
    @Log(title = "修改用户地址", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody UserAddress userAddress) {
        Assert.notNull(userAddress.getAddressId(), "用户地址ID不能为空");
        UserAddress address = userAddressService.selectUserAddressByAddressId(userAddress.getAddressId());
        Assert.notNull(address, "用户地址不存在");
        Assert.isTrue(address.getUserId().equals(SecurityUserUtils.getUserId()), "只能操作自己的地址");
        return toAjax(userAddressService.updateUserAddress(userAddress));
    }

    /**
     * 删除用户地址
     */
    @ApiOperation("删除用户地址")
    @Log(title = "删除用户地址", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{addressIds}")
    public AjaxResult remove(@PathVariable Long[] addressIds) {
        return toAjax(userAddressService.deleteUserAddressByAddressIds(addressIds));
    }
}
